package kr.couponplay.android.activity.intro.command;

import java.io.File;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.Constants;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class FileCacheSettingCommand implements Command {

	@Override
	public void execute(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
		String fileCacheDir = makeFileCacheDir(context);
		
		int fileCacheCount = preferences.getInt(Constants.KEY_FILE_CACHE_COUNT, 0) + 1;
		
		Editor editor = preferences.edit();
		editor.putString(Constants.KEY_FILE_CACHE_ROOT_PATH, fileCacheDir);
		editor.putInt(Constants.KEY_FILE_CACHE_COUNT, fileCacheCount);
		editor.commit();
		AppContext.setFileCacheRootPath(fileCacheDir);
		AppContext.setFileCacheCount(fileCacheCount);
	}
	
	private String makeFileCacheDir(Context context) {
		File cacheDir = null;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), Constants.FILE_CACHE_ROOT_PATH);
		} else {
			cacheDir = context.getCacheDir();
		}
		
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
		return cacheDir.getPath();
	}
}
